// const { get } = require("jquery");

//商品列表
class List {
  constructor() {
    this.getData();
  }
  async getData() {
    let { data, status } = await axios.get("http://localhost:8888/goods/list");
    // console.log(data, status);
    //判断是否请求成功
    if (status != 200 && data.code != 1) return;
    // console.log(data.list);
    let html = "";
    data.list.forEach((element) => {
      html += `<li class="yui3-u-1-5" data-id=${element.goods_id}>
            <div class="p-img" onclick="List.aaa(this)">
                <a href="#none"><img src="${element.img_big_logo}"></a>
            </div>
            <div class="attr"><em>${element.title}</em></div>
            <div class="price"><strong><em>¥</em><i>${element.current_price}</i></strong><s>￥${element.price}</s></div>
            <div class="sold"><span>已售${element.sale_type}</span><img src="./uploads/state_07.png" alt=""><span>剩余${element.goods_number}件</span>
            </div>
            <div class="operate">
                <a href="#1" onclick="List.addCart()">立即抢购</a>
            </div>
        </li>`;
    });
    //追加到页面当中去
    this.$(".goods-list ul").innerHTML = html;
  }
  static aaa = (e) => {
    // console.log(e);
    let goodsId = e.parentNode.dataset.id;
    // console.log(goodsId);
    localStorage.setItem("id", goodsId);
    location.href = "./item.html";
  };
  //立即抢购点击事件,追加到购物车
  //static静态方法,直接通过类进行调用
  static addCart() {
    // console.log(this);
    //获取事件源
    let tar = window.event.target;
    // console.log(tar);
    //获取商品id
    let goodsId = tar.parentNode.parentNode.dataset.id;
    // console.log(goodsId);
    //获取用户id
    let userId = localStorage.getItem("user_id");
    let token = localStorage.getItem("token");
    // console.log(userId, token);
    //判断是否登录
    if (!userId) location.href = "./login.html";
    //此服务器所有需要登录后使用的接口,均在请求头内携带authorization字段, 传递token值方可
    axios.defaults.headers.common["authorization"] = token;
    //设置参数编码方式
    axios.defaults.headers["Content-Type"] =
      "application/x-www-form-urlencoded";
    //发送ajax请求
    let str = `id=${userId}&goodsId=${goodsId}`;
    axios
      .post("http://localhost:8888/cart/add", str)
      .then(({ data, status }) => {
        //解构赋值
        if (data.code == 1 && status == 200) {
          layer.confirm(
            "要去购物车结算吗?",
            {
              btn: ["是的", "不去"], //按钮
            },
            function () {
              //跳转到指定页面
              location.assign("./cart.html");
            }
          );
        }
        //判断code值是否为0 为0则没有登录
        if (data.code == 0 && status == 200) {
          location.assign("./login.html");
        }
      })
      .catch((red) => {});
  }
  //获取节点的方法
  $(ele) {
    let res = document.querySelectorAll(ele);
    return res.length == 1 ? res[0] : res;
  }
}
new List();
